
package com.putao.album.main;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.db.MessageHelper;
import com.putao.album.db.tables.InMessage;
import com.putao.album.dialog.ConfirmDialogBuilder;
import com.putao.album.dialog.MessageDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.fileupload.FileUploadManager;
import com.putao.album.main.url.SlidingMenu;
import com.putao.album.main.url.ToggleListener;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.NetUtil;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.UmengPushHelper;
import com.putao.album.util.UmengUpdateHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by yanglun on 15/4/21.
 */
public class AlbumHomeActivity extends BaseActivity implements ToggleListener {
    private SlidingMenu mSlidingMenu;
    private LeftFragment leftFragment;
    private RightFragment rightFragment;
    private HomeFragment centerFragment;
    private FragmentTransaction t;
    private long clickTime = 0; //记录第一次点击的时间 
    MessageHelper msghelp;

    @Override
    public void doBefore() {
        super.doBefore();
        ActivityHelper.startActivity(mActivity,ActivityNewPhotos.class);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_album_home;
    }

    @Override
    public void doInitSubViews(View view) {
        mSlidingMenu = (SlidingMenu) findViewById(R.id.slidingMenu);
        mSlidingMenu.setLeftView(getLayoutInflater().inflate(R.layout.left_frame, null));
        mSlidingMenu.setRightView(getLayoutInflater().inflate(R.layout.right_frame, null));
        mSlidingMenu.setCenterView(getLayoutInflater().inflate(R.layout.center_frame, null));
        mSlidingMenu.setToggleListener(this);
        t = this.getSupportFragmentManager().beginTransaction();
        leftFragment = new LeftFragment();
        rightFragment = new RightFragment();
        t.replace(R.id.left_frame, leftFragment);
        t.replace(R.id.right_frame, rightFragment);
        centerFragment = new HomeFragment();
        t.replace(R.id.center_frame, centerFragment);
        t.commit();
        EventBus.getDefault().register(this);
    }

    @Override
    public void doInitData() {
        UmengUpdateHelper.getInstance().autoUpdate(this);
        UmengPushHelper.getInstance().initPushAgent();
        msghelp = new MessageHelper(mContext);

        if (!NetUtil.isWifiEnable(mContext)) {
            new ConfirmDialogBuilder(mContext)
                    .setMessage("当前未连接WIFI,继续浏览\n可能会耗费大量数据流量!")
                    .setNegativeButton("我知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .Create()
                    .show();
        }

        FileUploadManager.getIntance().startUploadCurrentChildUnfinished(CommonUtils.getBabyId());
    }

    void checkMessage() {
        List<InMessage> tList = new ArrayList<InMessage>();
        List<InMessage> messageList = getInMessages(1);
        List<InMessage> messageList2 = getInMessages(2);
        if (messageList != null) {
            tList.addAll(messageList);
        }
        if (messageList2 != null) {
            tList.addAll(messageList2);
        }
        for (int i = 0; i < tList.size(); i++) {
            showMessageDialog(tList.get(i), tList.get(i).getType());
        }
    }

    private List<InMessage> getInMessages(final int type) {
        return msghelp.getInMessageByWhere(new HashMap<String, String>() {{
            put("baby_id", CommonUtils.getBabyId());
            put("type", String.valueOf(type));
        }});
    }

    private void showMessageDialog(final InMessage message, int type) {
        new MessageDialogBuilder(mContext).setMessage(message.getMessage_content()).setMessageType(type).Create().show();
        msghelp.deleteInMessage(new HashMap<String, String>() {{
            put("id", message.getId() + "");
        }});
    }

    @Override
    public void onResume() {
        super.onResume();
        checkMessage();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (!CommonUtils.isBackgroundUploadOpen()) {
            FileUploadManager.getIntance().stop();
        }
    }

    @Override
    public void onClick(View v) {

    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_LOGIN_OUT:
                finish();
                break;
            case PuTaoConstants.EVENTBUS_RECEIVE_MESSAGE:
                Bundle bundle = event.bundle;
                InMessage msg = (InMessage) bundle.getSerializable("message");
                int type = bundle.getInt("type", 1);
                if (msg != null) {
                    showMessageDialog(msg, type);
                }
                break;
            case PuTaoConstants.EVENTBUS_DELETE_OR_ADD_TAG_SUCCESS:
            case PuTaoConstants.EVENTBUS_ADD_OR_REMOVE_COLLECTION:
                if (leftFragment != null) {
                    leftFragment.querySideInfo();
                }
                break;
            case PuTaoConstants.EVENTBUS_DELETE_CHILD://删除宝宝
                if (leftFragment != null) {
                    leftFragment.querySideInfo();
                }
                if (centerFragment != null) {
                    centerFragment.initBabyDataes();
                }
                break;
            case PuTaoConstants.EVENTBUS_DELETE_LAST_CHILD:
                if (leftFragment != null) {
                    leftFragment.doInitDataes();
                }
                break;
        }
    }

    public void showLeft(boolean bShow) {
        mSlidingMenu.showLeftView(bShow);
    }

    public void showRight() {
        mSlidingMenu.showRightView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次返回键退出",
                    Toast.LENGTH_SHORT).show();
            clickTime = System.currentTimeMillis();
        } else {
            this.finish();
        }
    }

    @Override
    public void isToggleOpen(boolean bToggle) {
        centerFragment.showCoverPanel(bToggle);
    }
}
